<template>
  <div class="app-container">
    <Find :OriginalFilter="{ static: true }" :formList="formList" @findClicked="findClicked" />
    <div class="flex mt10" style="width: 100%; background-color: white">
      <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }">
        <JDialog
          :tableHeader="tableHeader"
          :width="73"
          @removeOne="removeOne"
          :currentTableRow="currentTableRow"
          @confirm="confirm"
          :unEdit="false"
          :unAdd="true"
        />
        <Table :tableHeader="tableHeader" :tableData="tableData" class="mt10" :isLoading="isLoading" @currentRow="currentRow" />
        <el-card shadow="never" :body-style="{ padding: '5px' }">
          <PageModule :PageData="{ total, buttonS: true }" @pageSizeChange="handleSizeChange" @pageChange="handleCurrentChange" />
        </el-card>
      </el-card>
      <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }">
        <div class="flex AIC">
          <h1 class="f16 mr10">考勤公休日定义</h1>
          <el-date-picker v-model="ym" :type="'month'" placeholder="请输入月份" :format="'YYYYMM'" :value-format="'YYYYMM'" />
          <!-- <el-input style="width: 100px; height: 26px;" v-model="ym" placeholder="请输入月份" clearable @change=""></el-input> -->
          <el-button class="primaryBth ml10" type="primary" @click="insertDate">插入当月周末日期</el-button>
          <JDialog
            :tableHeader="tableHeader2"
            :width="73"
            @removeOne="removeOne2"
            :currentTableRow="currentTableRow2"
            @confirm="confirm2"
            :unEdit="false"
          />
        </div>
        <Table @currentRow="currentRow2" :tableHeader="tableHeader2" :tableData="tableData2" class="mt10" :isLoading="isLoading2" />
      </el-card>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import LoginWork from '@/utils/LoginWork'
import { formateData } from '@/plugins/mixinJ'
import JMessage from '@/utils/JMessage'
export default defineComponent({
  name: 'TesInformationHomework'
})
</script>
<script lang="ts" setup>
import { i18n, Jzhcn } from '@/i18n'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import service from '@/utils/request'
import { debounce } from 'lodash'
import { onMounted, watch } from 'vue'
const today = new Date() as any
const year = today.getFullYear()
const month = String(today.getMonth() + 1).padStart(2, '0')
const ym = ref(year + month)
const formList = ref([
  {
    type: 'select',
    selectValue: '',
    selectP: '部门',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'input',
    inputPlaceholder: '请输入工号',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入姓名',
    inputValue: ''
  },
  {
    type: 'date',
    dateLabel: '出勤日期',
    dateValue: ''
  },
  {
    type: 'button',
    checkboxLabel: '导入考勤资料(*.xls)'
  }
])

// 表一模块
// 表一按钮
const upFile = ref()
const findClicked = async (content: string) => {
  if (content === '置空') {
    formList.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
    })
  }
  if (content === '导入考勤资料(*.xls)') {
    upload()
  }
}
const upload = async () => {
  const fileType = ['xls', 'xlsx']
  const inputFile = document.createElement('input')
  const maxFileSizeMb = 2
  const maxFilesSizeBytes = maxFileSizeMb * 1024 * 1024
  inputFile.type = 'file'
  inputFile.style.display = 'none'
  document.body.appendChild(inputFile)
  inputFile.addEventListener('change', async function () {
    const files = inputFile.files as any // 获取文件数组
    const file = files[0] // 获取第一个文件对象
    const fileExtension = file.name.split('.').pop()
    if (!fileType.includes(fileExtension as any)) {
      JMessage.warning('上传的文件格式只能是 xls, xlsx')
      document.body.removeChild(inputFile)
      return false
    }
    if (file.size > maxFilesSizeBytes) {
      JMessage.warning('文件大小不能超过2MB!!!')
      document.body.removeChild(inputFile)
      return
    }
    const formData = new FormData()
    formData.append('file', file) // 添加文件对象及文件名
    const result = (await LoginWork.post('/emp/ImportAttendanceData', formData)) as any
    if (result.code === 200) {
      JMessage.success(result.message)
      getTableList()
    } else {
      JMessage.error(result.message)
    }
    upFile.value = formData
  })
  inputFile.click()
}
const tableData = ref([])
const isLoading = ref(true)
// 分页器
const currentPage = ref(1)
const pageSize = ref(40)
const total = ref(0)
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getTableList()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getTableList()
}
// 获取表数据
const getTableList = debounce(async () => {
  isLoading.value = true
  let tableDataList = await service.post<any, any>('/emp/AttendanceDataQuery', {
    deptName: formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '部门')
      ?.selectValue,
    inTime: formList.value.find((item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '出勤日期')
      ?.dateValue?.[0],
    outTime: formList.value.find((item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '出勤日期')
      ?.dateValue?.[1],
    workerId: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入工号'
    )?.inputValue,
    workerName: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入姓名'
    )?.inputValue,
    years: '',
    pageNum: currentPage.value,
    pageSize: pageSize.value
  })
  isLoading.value = false
  tableData.value = tableDataList.list.map((item: any) => {
    if (item.status === '0') item.backgroundColor = 'red'
    return item
  })
  total.value = tableDataList.total
  currentRow()
}, 500)
onMounted(() => {
  getTableList()
})
watch(
  () =>
    formList.value.map((item: any) => {
      item.selectValue, item.inputValue, item.dateValue, item.checked
    }),
  () => {
    getTableList()
  }
)
const tableHeader = ref([
  {
    change: true,
    label: '部门',
    prop: 'deptName'
  },
  {
    change: true,
    label: '工号',
    prop: 'workerId'
  },
  {
    backgroundColor: true,
    change: true,
    label: '姓名',
    prop: 'workerName'
  },
  {
    label: '日期',
    prop: 'ddate'
  },
  {
    label: '迟到次数',
    prop: 'lateNums'
  },
  {
    label: '迟到分钟',
    prop: 'lateMinutes'
  },
  {
    label: '早退次数',
    prop: 'earlyNums'
  },
  {
    label: '早退分钟',
    prop: 'earlyMinutes'
  },
  {
    label: '请假分钟',
    prop: 'leaveDays'
  },
  {
    label: '矿工分钟',
    prop: 'outDays'
  },
  {
    change: true,
    label: '正班时数',
    prop: 'workHours'
  },
  {
    change: true,
    label: '检核标记',
    prop: 'cfmFlag'
  }
])
// 点击表给另一张表传数据
const currentTableRow = ref({}) as any
const currentRow = async (row: any = tableData.value[0] ? tableData.value[0] : {}) => {
  currentTableRow.value = row
  getTableList2()
}

// Dialog确认添加/修改按钮
const confirm = async (obj: any, dialogVisible: any, title: any) => {
  // 打印出obj的值
  const tempList = formateData([obj]) as any
  // 向服务器发送请求，更新外派单信息
  if (title === '添加') {
  } else if (title === '修改') {
    const res = (await LoginWork.post(`/emp/AttendanceDataUpdate`, {
      ...tempList[0]
    })) as any
    // 判断请求是否成功
    if (res.code === 200) {
      JMessage.success(res.message)
    } else {
      JMessage.error(res.message)
    }
  }
  // 关闭弹出框
  dialogVisible.value = false
  // 重新获取表格数据
  getTableList()
}
// 删除
const removeOne = async () => {
  // 向服务器发送请求，更新外派单信息
  const res = (await LoginWork.post(`/emp/AttendanceDataDel`, currentTableRow.value)) as any
  // 判断请求是否成功
  if (res.code === 200) {
    JMessage.success(res.message)
  } else {
    JMessage.error(res.message)
  }
  // 重新获取表格数据
  getTableList()
}

// 表二模块
const tableData2 = ref([])
const isLoading2 = ref(true)
// 获取表数据
const getTableList2 = debounce(async () => {
  isLoading2.value = true
  let tableDataList = await service.post<any, any>(`/emp/AttendancePublicHolidays?years=${ym.value}`)
  isLoading2.value = false
  tableData2.value = tableDataList.map((item: any) => {
    return { date: item }
  })
  currentRow2()
}, 500)
const tableHeader2 = ref([
  {
    label: '公休日期',
    prop: 'date'
  }
])
watch(ym, () => {
  getTableList2()
})
const insertDate = async () => {
  const res = (await LoginWork.post(`/emp/InsertTheWeekendDateOfTheCurrentMonth?years=${ym.value}`)) as any
  if (res.code === 200) {
    JMessage.success(res.message)
    getTableList2()
  } else {
    JMessage.error(res.message)
  }
}
// 点击表给另一张表传数据
const currentTableRow2 = ref({}) as any
const currentRow2 = async (row: any = tableData2.value[0]) => {
  currentTableRow2.value = row
}
// Dialog确认添加/修改按钮
const confirm2 = async (obj: any, dialogVisible: any, title: any) => {
  // 打印出obj的值
  const tempList = formateData([obj]) as any
  // 向服务器发送请求，更新外派单信息
  if (title === '添加') {
    const res = (await LoginWork.post(`/emp/psHoliday2Add?years=${tempList[0].date}`)) as any
    // 判断请求是否成功
    if (res.code === 200) {
      JMessage.success(res.message)
    } else {
      JMessage.error(res.message)
    }
  } else if (title === '修改') {
    const res = (await LoginWork.post(`/emp/psHoliday2Update?newYears=${tempList[0].date}&years=${currentTableRow2.value.date}`)) as any
    // 判断请求是否成功
    if (res.code === 200) {
      JMessage.success(res.message)
    } else {
      JMessage.error(res.message)
    }
  }
  // 关闭弹出框
  dialogVisible.value = false
  // 重新获取表格数据
  getTableList2()
}
// 删除
const removeOne2 = async () => {
  // 向服务器发送请求，更新外派单信息
  const res = (await LoginWork.post(`/emp/psHoliday2Del?years=${currentTableRow2.value.date}`)) as any
  // 判断请求是否成功
  if (res.code === 200) {
    JMessage.success(res.message)
  } else {
    JMessage.error(res.message)
  }
  // 重新获取表格数据
  getTableList2()
}

const getSelectList = async () => {
  const mtlDept = formList.value.find(
    (item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '部门'
  ) as any
  const mtlDeps = await service.get<any, any>('/back/deptQuery')
  mtlDeps.forEach((Vendor: any) => {
    mtlDept.selectOptions.push({
      optionLabel: Vendor.deptName,
      optionValue: `${Vendor.deptName}`,
      optionKey: `${Vendor.deptNo} `
    })
  })
}
onMounted(() => {
  getSelectList()
})
</script>

<style lang="less" scoped></style>
